﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace TopVisionVideoStream
{
    public class TVHttpRequest : IDisposable
    {
        //private HttpClient client;

        private int errCount = 0;

        public async Task<string> PostAsync(string url, Dictionary<string, string> param)
        {
            using (HttpClient client = new HttpClient())
            {
                var content = new FormUrlEncodedContent(param);
                var result = client.PostAsync(url, content).Result;
                return await result.Content.ReadAsStringAsync();
            }
        }

        public async Task<string> PostAsync(string url, string json)
        {
            using (HttpClient client = new HttpClient())
            {
                client.Timeout = TimeSpan.FromSeconds(10);
                client.DefaultRequestHeaders.TryAddWithoutValidation(TVHttpRequestContentType.contentType, TVHttpRequestContentType.application_json);
                StringContent content = new StringContent(json, Encoding.UTF8, TVHttpRequestContentType.application_json);
                var result = client.PostAsync(url, content).Result;
                return await result.Content.ReadAsStringAsync();
            }
        }

        public string Post(string url, string json)
        {
            using (HttpClient client = new HttpClient())
            {
                try
                {
                    client.DefaultRequestHeaders.TryAddWithoutValidation(TVHttpRequestContentType.contentType, TVHttpRequestContentType.application_json);
                    StringContent content = new StringContent(json, Encoding.UTF8, TVHttpRequestContentType.application_json);
                    var result = client.PostAsync(url, content).Result;
                    return result.Content.ReadAsStringAsync().Result;
                }
                catch (Exception ex)
                {
                    errCount++;

                    if (errCount == 10) return "";

                    return Post(url, json);
                }
            }
        }

        public void Dispose()
        {

        }
    }

    public class TVHttpRequestContentType
    {
        public const string contentType = "Content-Type";
        public const string application_json = "application/json";
    }
}
